package tw.miku.util;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.Collection;

import org.apache.mina.core.buffer.IoBuffer;

import tw.miku.model.ISendable;

public final class BufferUtility
{

	private static final Charset charset = Charset.forName("UTF-8");

	public BufferUtility()
	{

	}

	public static final IoBuffer newInstance()
	{
		return IoBuffer.allocate(100).setAutoExpand(true);
	}

	public static final IoBuffer clone(IoBuffer ioBuffer)
	{
		IoBuffer result = IoBuffer.allocate(ioBuffer.limit());
		result.put(ioBuffer);
		result.flip();
		ioBuffer.position(0);
		return result;
	}

	public static final String readString(IoBuffer ioBuffer)
	{
		int length = (int) ioBuffer.getUnsignedInt();
		if (length == 0)
		{
			return "";
		}
		else
		{
			byte[] msg = new byte[length];
			ioBuffer.get(msg, 0, length);
			String message = new String(msg, charset);
			return message;
		}
	}

	public static final void writeArray(IoBuffer ioBuffer,
			Collection<? extends ISendable> infos)
			throws CharacterCodingException
	{
		int size = infos.size();
		if (size == 0)
		{
			ioBuffer.putUnsignedInt(0);
		}
		else
		{
			ioBuffer.putUnsignedInt(size);
			for (ISendable info : infos)
			{
				ioBuffer.put(info.getInfo());
			}
		}
	}

	public static final void writeString(IoBuffer ioBuffer, String value)
			throws CharacterCodingException
	{
		if (value.length() == 0)
		{
			ioBuffer.putUnsignedInt(0);
		}
		else
		{
			int currentPosition = ioBuffer.position();

			ioBuffer.position(currentPosition + 4);
			ioBuffer.putString(value, charset.newEncoder());
			int newPosition = ioBuffer.position();
			int messageLength = newPosition - currentPosition - 4;
			ioBuffer.position(currentPosition);
			ioBuffer.putUnsignedInt(messageLength);
			ioBuffer.position(newPosition);

			// var currentPosition:int = this.position;
			// this.position = currentPosition + 4;
			// writeMultiByte(value, "utf-8");
			// var newPosition:int = this.position;
			// var messageLength:int = newPosition - currentPosition - 4;
			// this.position = currentPosition;
			// writeUnsignedInt(messageLength);
			// this.position = newPosition;
		}
	}

}
